/**
 * @file usersSlice.js
 * @description 用户状态管理
 */
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { initRoles, initAdminUsers } from '../utils/initData';

// 初始状态
const initialState = {
  users: [],
  roles: [],
  isLoading: false,
  error: null,
};

// 获取所有用户
export const fetchAllUsers = createAsyncThunk(
  'users/fetchAllUsers',
  async () => {
    try {
      // 从本地存储获取用户列表
      const adminUsers = JSON.parse(localStorage.getItem('adminUsers') || '[]');
      const regularUsers = JSON.parse(localStorage.getItem('users') || '[]');
      
      // 合并管理员用户和普通用户
      const allUsers = [...adminUsers, ...regularUsers];
      
      return allUsers;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  }
);

// 获取所有角色
export const fetchAllRoles = createAsyncThunk(
  'users/fetchAllRoles',
  async () => {
    try {
      // 从本地存储获取角色列表
      const roles = JSON.parse(localStorage.getItem('roles') || '[]');
      return roles;
    } catch (error) {
      console.error('获取角色列表失败:', error);
      throw error;
    }
  }
);

// 更新用户角色
export const updateUserRole = createAsyncThunk(
  'users/updateUserRole',
  async ({ userId, roleId }, { getState }) => {
    try {
      // 从本地存储获取用户列表
      const adminUsers = JSON.parse(localStorage.getItem('adminUsers') || '[]');
      
      // 查找并更新用户角色
      const updatedUsers = adminUsers.map(user => {
        if (user.id === userId) {
          return { ...user, roleId };
        }
        return user;
      });
      
      // 更新本地存储
      localStorage.setItem('adminUsers', JSON.stringify(updatedUsers));
      
      return { userId, roleId };
    } catch (error) {
      console.error('更新用户角色失败:', error);
      throw error;
    }
  }
);

// 添加管理员用户
export const addAdminUser = createAsyncThunk(
  'users/addAdminUser',
  async (userData, { getState }) => {
    try {
      // 从本地存储获取用户列表
      const adminUsers = JSON.parse(localStorage.getItem('adminUsers') || '[]');
      
      // 添加新用户
      const updatedUsers = [...adminUsers, userData];
      
      // 更新本地存储
      localStorage.setItem('adminUsers', JSON.stringify(updatedUsers));
      
      return userData;
    } catch (error) {
      console.error('添加管理员用户失败:', error);
      throw error;
    }
  }
);

// 删除管理员用户
export const deleteAdminUser = createAsyncThunk(
  'users/deleteAdminUser',
  async (userId, { getState }) => {
    try {
      // 从本地存储获取用户列表
      const adminUsers = JSON.parse(localStorage.getItem('adminUsers') || '[]');
      
      // 过滤掉要删除的用户
      const updatedUsers = adminUsers.filter(user => user.id !== userId);
      
      // 更新本地存储
      localStorage.setItem('adminUsers', JSON.stringify(updatedUsers));
      
      return userId;
    } catch (error) {
      console.error('删除管理员用户失败:', error);
      throw error;
    }
  }
);

// 添加角色
export const addRole = createAsyncThunk(
  'users/addRole',
  async (roleData, { getState }) => {
    try {
      // 从本地存储获取角色列表
      const roles = JSON.parse(localStorage.getItem('roles') || '[]');
      
      // 添加新角色
      const updatedRoles = [...roles, roleData];
      
      // 更新本地存储
      localStorage.setItem('roles', JSON.stringify(updatedRoles));
      
      return roleData;
    } catch (error) {
      console.error('添加角色失败:', error);
      throw error;
    }
  }
);

// 更新角色
export const updateRole = createAsyncThunk(
  'users/updateRole',
  async (roleData, { getState }) => {
    try {
      // 从本地存储获取角色列表
      const roles = JSON.parse(localStorage.getItem('roles') || '[]');
      
      // 查找并更新角色
      const updatedRoles = roles.map(role => {
        if (role.id === roleData.id) {
          return { ...role, ...roleData };
        }
        return role;
      });
      
      // 更新本地存储
      localStorage.setItem('roles', JSON.stringify(updatedRoles));
      
      return roleData;
    } catch (error) {
      console.error('更新角色失败:', error);
      throw error;
    }
  }
);

// 删除角色
export const deleteRole = createAsyncThunk(
  'users/deleteRole',
  async (roleId, { getState }) => {
    try {
      // 从本地存储获取角色列表
      const roles = JSON.parse(localStorage.getItem('roles') || '[]');
      
      // 过滤掉要删除的角色
      const updatedRoles = roles.filter(role => role.id !== roleId);
      
      // 更新本地存储
      localStorage.setItem('roles', JSON.stringify(updatedRoles));
      
      return roleId;
    } catch (error) {
      console.error('删除角色失败:', error);
      throw error;
    }
  }
);

// 验证管理员登录
export const validateAdminLogin = createAsyncThunk(
  'users/validateAdminLogin',
  async ({ username, password }, { getState }) => {
    try {
      // 从本地存储获取管理员用户列表
      const adminUsers = JSON.parse(localStorage.getItem('adminUsers') || '[]');
      
      // 查找匹配的用户
      const user = adminUsers.find(
        user => user.username === username && user.password === password
      );
      
      return user || null;
    } catch (error) {
      console.error('验证管理员登录失败:', error);
      throw error;
    }
  }
);

// 用户状态切片
const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    // 可以添加其他同步reducer
  },
  extraReducers: (builder) => {
    // 处理获取所有用户
    builder.addCase(fetchAllUsers.pending, (state) => {
      state.isLoading = true;
    });
    builder.addCase(fetchAllUsers.fulfilled, (state, action) => {
      state.users = action.payload;
      state.isLoading = false;
    });
    builder.addCase(fetchAllUsers.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.error.message;
    });
    
    // 处理获取所有角色
    builder.addCase(fetchAllRoles.pending, (state) => {
      state.isLoading = true;
    });
    builder.addCase(fetchAllRoles.fulfilled, (state, action) => {
      state.roles = action.payload;
      state.isLoading = false;
    });
    builder.addCase(fetchAllRoles.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.error.message;
    });
    
    // 处理更新用户角色
    builder.addCase(updateUserRole.fulfilled, (state, action) => {
      const { userId, roleId } = action.payload;
      state.users = state.users.map(user => {
        if (user.id === userId) {
          return { ...user, roleId };
        }
        return user;
      });
    });
    
    // 处理添加管理员用户
    builder.addCase(addAdminUser.fulfilled, (state, action) => {
      state.users.push(action.payload);
    });
    
    // 处理删除管理员用户
    builder.addCase(deleteAdminUser.fulfilled, (state, action) => {
      state.users = state.users.filter(user => user.id !== action.payload);
    });
    
    // 处理添加角色
    builder.addCase(addRole.fulfilled, (state, action) => {
      state.roles.push(action.payload);
    });
    
    // 处理更新角色
    builder.addCase(updateRole.fulfilled, (state, action) => {
      const index = state.roles.findIndex(role => role.id === action.payload.id);
      if (index !== -1) {
        state.roles[index] = action.payload;
      }
    });
    
    // 处理删除角色
    builder.addCase(deleteRole.fulfilled, (state, action) => {
      state.roles = state.roles.filter(role => role.id !== action.payload);
    });
  },
});

// 初始化管理员数据
export const initAdminData = () => (dispatch) => {
  // 初始化角色数据
  const roles = initRoles();
  dispatch({ type: 'users/fetchAllRoles/fulfilled', payload: roles });
  
  // 初始化管理员用户数据
  const adminUsers = initAdminUsers();
  dispatch({ type: 'users/fetchAllUsers/fulfilled', payload: adminUsers });
};

export default usersSlice.reducer;